package com.github.maojx0630.wechat.bot.common;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import java.io.File;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class TempUtil implements ApplicationContextAware {
  private static final File TEMP_PATH =
      new File(System.getProperty("java.io.tmpdir")+File.separator + "com.github.maojx0630");

  @SneakyThrows
  public static File getTempFile(String fileType) {
    File file = File.createTempFile(IdUtil.fastSimpleUUID(), "." + fileType, TEMP_PATH);
    file.deleteOnExit();
    log.info("创建临时文件:{}", file.getAbsolutePath());
    return file;
  }

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    if (TEMP_PATH.exists()) {
      FileUtil.del(TEMP_PATH);
    }
    TEMP_PATH.mkdirs();
    log.info("临时文件目录:{}", TEMP_PATH);
  }
}
